<?php

namespace app\modules\weixin\controllers;

use app\common\components\BaseWebController;
use app\common\services\ConstantMapServices;
use app\common\services\UrlServices;
use app\common\services\UtilService;
use app\common\services\weixin\RequestService;
use app\models\activity\ActivityPrize;
use app\models\HongbaoLog;
use app\models\member\Member;
use app\models\StoreInformaction;
use app\models\YaojiangRecord;
use Yii;
use yii\helpers\Json;

class TestController extends BaseWebController
{
    public function actionIndex()
    {
      var_dump(123);die;
//        if(\Yii::$app->session->get('user_info')->open_id == 'oH5oJuJyT0ahfpQ50LAJVEkQZyY8'){
        //            $result = $this->SetPrize('oH5oJuJyT0ahfpQ50LAJVEkQZyY8',1.01);
        //            var_dump($result);die;
        //        }
        // if (time() > 1510927200) {
        //     return $this->redirect(UrlServices::buildWWWUrl('/yaojiang/pages/over.html'));
        // }
         var_dump(Yii::$app->session->get('user_info'));die;
        if (Yii::$app->session->get('user_info')) {
            $js_info = RequestService::jsapi_ticket_config(RequestService::GetUrl(true));
            return $this->render('index', ['js_info' => $js_info]);
        } else {
            return $this->redirect(UrlServices::buildMUrl('/oauth/bind'));
        }
    }

    public function actionScreen()
    {
        $session = Yii::$app->session->get('user_info');
        if ($session->open_id) {
            $js_info = RequestService::jsapi_ticket_config(RequestService::GetUrl(true));
            return $this->render('screen', ['js_info' => $js_info]);
        } else {
            return $this->redirect('/weixin/activity/index');
        }
    }

    public function actionLong()
    {
        $session = Yii::$app->session->get('user_info');
        if ($session->open_id) {$js_info = RequestService::jsapi_ticket_config(RequestService::GetUrl(true));
            return $this->render('long', ['js_info' => $js_info]);
        } else {
            return $this->redirect('/weixin/activity/index');
        }
    }

    public function actionCheckPrize()
    {
        $session = Yii::$app->session->get('user_info');
//        if (!isset($session->open_id)) {
//            return $this->renderJson([], '请在微信中打开~~', -3);
//        }

        $activity_info = ActivityPrize::findOne(['id' => 1]);

//        if (time() < $activity_info->ks_time) {
//            return Json::encode(['code' => -200, 'msg' => '活动还没有开始呢']);
//        }
//        if (time() > $activity_info->js_time) {
//            return Json::encode(['code' => -200, 'msg' => '活动已经结束了']);
//        }
        //查询该用户是否中奖
        $sql = "SELECT * FROM `yaojiang_record` WHERE (`open_id`= '".$session->open_id."') AND (TO_DAYS(FROM_UNIXTIME(create_time))=TO_DAYS(NOW()))";
        $is_win = YaojiangRecord::findBySql($sql)->asArray()->count();
        var_dump($is_win);die;
        $is_win = YaojiangRecord::find()->where(['open_id' => $session->open_id])->andWhere(['is_winning' => 1])->asArray()->one();
        $win_count = YaojiangRecord::find()->where(['open_id' => $session->open_id])->count();
        $member_info = Member::find()->where(['open_id' => $session->open_id])->asArray()->one();
//        if ($win_count == 2) {
//            return Json::encode(['code' => -200, 'msg' => '您已经中过奖,召唤小伙伴来玩吧']);
//        }
        return Json::encode(['code' => 200]);
    }

    public function actionGetPrize()
    {
        $com = Yii::$app->db;
        $sql = 'SELECT SUM(prize_num) as prize_count FROM activity_prize ';
        $command = $com->createCommand($sql);
        $prize_count = $command->queryOne();

        $session = \Yii::$app->session->get('user_info');
        $my_price_count = YaojiangRecord::find()->where(['open_id' => $session->open_id])->count();
        if (!isset($session->open_id)) {
            return $this->renderJson([], '请在微信中打开~~', -3);
        }

        if (Yii::$app->request->isAjax) {
            //判断用户是否是二次抽奖
            $member_info = Member::find()->where(['open_id' => $session->open_id])->one();
            if ($member_info->yaojiang_count == 1) {
                $member_info->yaojiang_count -= 1;
                $member_info->save(0);
            }
            $prize_token = trim(\Yii::$app->request->post('prize_token', ''));

            if ($prize_token != 'ee976f20c81815b2') {
                return Json::encode(['code' => -200, 'msg' => '系统出错的,请稍后重试~~']);
            }

            $prize = ActivityPrize::find()->where(['>', 'prize_num', 0])->asArray()->all();
            $rid = UtilService::getRand($prize); //根据概率获取奖项ID
            $rid_type = explode('_', $rid['type']);
            if (!$rid['type']) {
                return Json::encode(['code' => -200, 'msg' => '系统出错请稍后再试试']);
            }
            //当获奖 $rid_type == '折扣券'是在store_information表随机取出一个奖品
            $store = new StoreInformaction();
            if ($rid_type[0] == '折扣券') {
                $store_id = mt_rand(1, 34);
                // $store_id = 1;
                $store_info = $store->getStore($store_id);
                $rid['store_info'] = $store_info;
            }
            if ($rid_type[0] == 'hongbao') {
                //发送红包
                $result = $this->SetPrize($session->open_id, $rid['prize_money']);

                if ($result['result_code'] != 'SUCCESS') {
                    $prize_now_arr = ActivityPrize::find()->where(['id' => 6])->one();
                    $prize_now_arr->prize_num = $prize_now_arr->prize_num - 1;
                    $prize_now_arr->update_time = time();
                    $prize_now_arr->update(0);

                    //获取电子券信息
                    $base_store_info = $store->getBaseStore();
                    if ($store->editStore($base_store_info['id'])) {
                        $yaojiang_record = new YaojiangRecord();
                        $yaojiang_record->ip = UtilService::getIP();
                        $yaojiang_record->open_id = $session->open_id;
                        $yaojiang_record->nickname = $session->nickname;
                        $yaojiang_record->is_winning = 1;
                        $yaojiang_record->prize = 6;
                        $yaojiang_record->prize_name = '折扣券';
                        $yaojiang_record->stroe_id = $base_store_info['id'];
                        $yaojiang_record->update_time = time();
                        $yaojiang_record->create_time = time();
                        $yaojiang_record->save(0);
                    }
                }
            }

            if ($rid_type[0] == '餐巾纸' || $rid_type[0] == '折扣券') {
                \Yii::$app->session->set('prize_info', $rid);
            }

            //如果中奖，修改其相对的奖品数量
            $prize_now_arr = [];
            if ($rid['type']) {
                $prize_now_arr = ActivityPrize::find()->where(['id' => $rid['id']])->one();
                $prize_now_arr->prize_num = $prize_now_arr->prize_num - 1;
                $prize_now_arr->update_time = time();
                $prize_now_arr->save(0);
                //修改store_information表中数据
                if ($rid_type[0] == '折扣券') {
                    $store->editStore($rid['store_info']['id']);
                }
            }

            //写摇奖数据表中
            $yaojiang_record = new YaojiangRecord();
            $yaojiang_record->ip = UtilService::getIP();
            $yaojiang_record->open_id = $session->open_id;
            $yaojiang_record->nickname = $session->nickname;
            if ($rid['type']) {
                $yaojiang_record->is_winning = 1;
                //获取用户获奖类型
                $temp_arr = $rid['type'];
                $temp_type = $this->getPrizeType($temp_arr);
                $yaojiang_record->prize = $temp_type;
                $yaojiang_record->prize_name = $rid['type'];
                if ($yaojiang_record->prize == 6) {
                    $yaojiang_record->store_id = $rid['store_info']['id'];
                }
                $hongbao_arr = [1, 2, 3, 4];
                if (in_array($temp_type, $hongbao_arr) == true) {
                    $yaojiang_record->is_receive = 1;
                }
            }
            $yaojiang_record->update_time = time();
            $yaojiang_record->create_time = time();
            $yaojiang_record->save(0);

            return Json::encode(['code' => 200]);
        }
        $js_info = RequestService::jsapi_ticket_config(RequestService::GetUrl(true));
        return $this->render('event', ['prize_count' => $prize_count, 'js_info' => $js_info, 'my_prize_count' => $my_price_count]);
    }

    public function actionPrizeList()
    {
        $user_info = Yii::$app->session->get('user_info');
        if ($user_info) {
            $prize_info = YaojiangRecord::find()->joinWith('store')->where(['open_id' => $user_info['open_id']])->asArray()->all();

            return $this->render('prize_list', ['prize_info' => $prize_info]);
        } else {
            return $this->redirect('/weixin/activity/index');
        }
    }

    public function actionMyPrize()
    {
        if (Yii::$app->session->get('user_info')) {
            $prize_id = Yii::$app->request->get('id', 0);
            if ($prize_id) {
                $prize_info = YaojiangRecord::find()->joinWith('store')->where(['yaojiang_record.id' => $prize_id])->asArray()->one();
                return $this->render('myprize', ['info' => $prize_info]);
            }
        } else {
            return $this->redirect('/weixin/activity/index');
        }
    }

    public function actionPrizeResult()
    {
        $is_ok = Yii::$app->request->get('is_ok', '');
        $user_info = Yii::$app->session->get('user_info');
        if (!$user_info) {
            return $this->redirect('/weixin/activity/index');
        }
        $prize_info = [];
        if ($is_ok && $user_info) {
            $prize_info = YaojiangRecord::find()->joinWith('store')->where(['open_id' => $user_info->open_id])->orderBy(['create_time' => SORT_DESC])->asArray()->one();
            $prize_count = YaojiangRecord::find()->where(['open_id' => $user_info->open_id])->count();
        }
        $js_info = RequestService::jsapi_ticket_config(RequestService::GetUrl(true));
        return $this->render('prize_result', ['is_ok' => $is_ok, 'info' => $prize_info, 'prize_count' => $prize_count, 'js_info' => $js_info]);
    }

    public function actionCash()
    {
        $verfiy_code = '909388';
        $code = \Yii::$app->request->post('code', '');
        $prize_id = Yii::$app->request->post('id', 0);
        if (empty($code)) {
            return $this->renderJson([], '请填写验证码~~', -1);
        }
        $session = Yii::$app->session->get('user_info');
        if ($code == $verfiy_code) {
            $prize_info = YaojiangRecord::find()->where(['open_id' => $session->open_id, 'id' => $prize_id])->andWhere(['is_winning' => 1, 'prize' => [4, 5, 6]])->one();
            $prize_info->is_receive = 1;
            $prize_info->update_time = time();
            $prize_info->save(0);

            return $this->renderJson([], '验证成功~~');
        }
    }

    public function actionAddChance()
    {
        if (Yii::$app->request->isAjax) {
            $open_id = Yii::$app->request->post('open_id', '');
            $member_info = Member::find()->where(['open_id' => $open_id])->one();
            if ($member_info) {
                $member_info->yaojiang_count += 1;
                $member_info->save(0);
                return Json::encode(['code' => 200, ]);
            } else {
                return Json::encode(['code' => -200, 'msg' => '系统出错,请稍后再试试']);
            }
        }
    }

    private function SetPrize($openid, $amount)
    {
        $rtime = time();
        $weixin_info = \Yii::$app->params['weixin'];
        $mch_billno = $weixin_info['wxPay_mch_id'] . date('YmdHis', $rtime) . rand(1000, 9999);
        $nonce_str = md5(UtilService::getRandChar(10) . $rtime);
        $__construct = [
            'nonce_str' => $nonce_str,
            'mch_billno' => $mch_billno, //商户订单号
            'mch_id' => $weixin_info['wxPay_mch_id'], //商户号
            'wxappid' => $weixin_info['appid'], //公众账号appid
            'send_name' => $weixin_info['wxPay_name'], //商户名称
            're_openid' => $openid, //用户openid
            'total_amount' => $amount * 100, //付款金额，单位分
            'total_num' => 1, //红包发放总人数
            'wishing' => '心意满满,恭喜你获得' . $amount . '红包', //红包祝福语
            'client_ip' => '121.196.205.70', //调用接口的机器Ip地址
            'act_name' => '九州新世界红包', //活动名称
            'remark' => '常州购物中心11.17店庆盛典，全城乐享好礼', //备注信息
        ];
        ksort($__construct);
        $string = UtilService::ToUrlParams($__construct);
        //签名步骤二：在string后加入KEY
        $string = $string . '&key=' . $weixin_info['wxPay_key'];
        //签名步骤三：MD5加密
        $string = md5($string);
        $__construct['sign'] = strtoupper($string);
        $xml = UtilService::ToXml($__construct);
//        $startTimeStamp = self::getMillisecond(); //请求开始时间
        $response = UtilService::postXmlCurl($xml, 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack', true, 10);
        $result = UtilService::FromXml($response);

        //self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
        $hongbao_log = new HongbaoLog();
        $hongbao_log->open_id = \Yii::$app->session->get('user_info')->open_id;
        $hongbao_log->account = $amount . '元';
        $hongbao_log->return_code = $result['return_code'];
        $hongbao_log->return_msg = $result['return_msg'];
        $hongbao_log->result_code = $result['result_code'];
        $hongbao_log->result_msg = json_encode($result);
        $hongbao_log->create_time = time();
        $hongbao_log->save(0);

        return $result;

//        echo ($xml);
        //$this->callback = json_decode($this->request_post(self::wxPayHongbaoUrl, urldecode(json_encode($__construct))));
    }

    private function getPrizeCount($data)
    {
        $res = array_column($data, 'prize_num', 'id');

        return $res;
    }

    private function modifyWeigth($data, $option, $condition)
    {
        foreach ($data as $key => $value) {
            if ($option[$value['id']] == 0) {
                //找到这个ID对应的概率
                $temp_arr = array_column($data, 'weight', 'id');
                $condition['weight'] = $condition['weight'] + $temp_arr[$value['id']];
                \Yii::$app->session->set('weight', $condition['weight']);
                unset($data[$key]);
            }
        }
        array_push($data, $condition);

        return array_values($data);
//        $this->show_dump(array_values($data));die;
    }

    private function getPrizeType($option)
    {
        $prize_type = ConstantMapServices::$prize_type;
        foreach ($prize_type as $key => $value) {
            if ($option == $key) {
                return $value;
            }
        }
    }
}
